package org.jvm.rtda.heap.symref;

import org.jvm.rtda.heap.*;
import org.jvm.rtda.heap.classLoader.KlassLoaderRegister;
import org.jvm.rtda.thread.Thread;

/**
 * 符号引用
 *
 * @author 王思翔
 * @date 2023/2/4
 */
public class SymRef {

    /**
     * 本类运行时常量池
     */
    protected ConstantPool cp;
    /**
     * 被引用类全类名
     */
    protected String className;
    /**
     * 被引用类的类信息，在引用符号解析时进行加载
     */
    protected Klass klass;

    public SymRef(ConstantPool cp, String className) {
        this.cp = cp;
        this.className = className;
    }

    /**
     * 解析被引用类信息
     *
     * @return
     */
    public Klass resolvedClass(Thread thread) {
        if (this.klass != null) {
            return this.klass;
        }
        //本类信息
        Klass thisClass = cp.getKlass();
        //通过本类的类加载器加载被引用类信息
        Klass thatClass = KlassLoaderRegister.loadKlass(this.className, thread);
        if (thatClass.isAccessibleTo(thisClass)) {
            this.klass = thatClass;
            return thatClass;
        }
        throw new RuntimeException("无被引用类访问权限");
    }
}
